package com.hunttown.mes.manage.controller._lbs;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.http.HttpClient;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.service.LbsServiceManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.LbsServiceDTO;
import com.hunttown.mes.rpc.domain.enums.lbs.ServiceLbsTypeEnum;
import com.hunttown.mes.rpc.domain.query.LbsServiceDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.common.utils.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2021-07-05 11:06:18
 */
@Controller
@RequestMapping(value = "/lbs/service")
public class LbsServiceController {

    private final static Logger logger = LoggerFactory.getLogger(LbsServiceController.class);

    private final LbsServiceManageService lbsServiceService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public LbsServiceController(LbsServiceManageService lbsServiceService, AnalysisManageManageService manageService) {
        this.lbsServiceService = lbsServiceService;
        this.manageService = manageService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, LbsServiceDTOQuery dtoQuery) {

        Page<LbsServiceDTO> dataPage = lbsServiceService.getForPage(dtoQuery);

        for (LbsServiceDTO item : dataPage.getItems()) {
            item.setLbsTypeName(ServiceLbsTypeEnum.getEnumByKey(item.getLbsType()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "lbs/service/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        LbsServiceDTO obj;

        if (id > 0) {
            obj = lbsServiceService.getById(id);
        } else {
            obj = new LbsServiceDTO();
            obj.setId(0);
        }
        model.addAttribute("Obj", obj);

        //地图服务提供商
        model.addAttribute("LbsTypeList", ServiceLbsTypeEnum.getEnumList());

        return "lbs/service/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, LbsServiceDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //region 【高德】调用高德接口生成唯一Key
            if (objDTO.getLbsType() == 1 && StringUtils.isBlank(objDTO.getServiceKey())) {
                String url = "https://tsapi.amap.com/v1/track/service/add";
                StringBuilder sb = new StringBuilder();
                sb.append("key=" + KeyConstants.LBS_GAODE_TRACKKEY);
                sb.append("&name=").append(objDTO.getServiceCode());
                String res = HttpClient.doPost(url, sb.toString(), 1);

                //logger.info(res); //这个日志会打印到后台

                //解析结果：{"data":{"name":"elt-allchannel-service","sid":364837},"errcode":10000,"errdetail":null,"errmsg":"OK"}
                JSONObject jsonObject = new JSONObject(res);
                if (!jsonObject.get("errcode").equals(10000)) {
                    map = OperateCode.CompositionResult(map, -10, "高德接口调用失败：" + jsonObject.get("errdetail"));
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                JSONObject dataObject = jsonObject.getJSONObject("data");
                objDTO.setServiceKey(dataObject.get("sid") + "");
            }
            //endregion

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = lbsServiceService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = lbsServiceService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = lbsServiceService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = lbsServiceService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        LbsServiceDTO obj = new LbsServiceDTO();
        obj.setId(id);

        if (id > 0) {
            obj = lbsServiceService.getById(id);
        }
        lbsServiceService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

}